const fs = require('fs');
const path = require('path');
const Mock = require('mockjs');

// JSON 文件路径
const productsFilePath = path.join(__dirname, 'products.json');

// 读取商品列表数据
const getProductList = () => {
    try {
        const productsData = fs.readFileSync(productsFilePath);
        return JSON.parse(productsData);
    } catch (error) {
        console.error('Error reading products file:', error);
        return [];
    }
};

// 保存商品列表数据到 JSON 文件
const saveProductList = (productsList) => {
    try {
        fs.writeFileSync(productsFilePath, JSON.stringify(productsList, null, 2));
    } catch (error) {
        console.error('Error saving products file:', error);
    }
};

// 生成初始商品数据
let productList = getProductList();
if (productList.length === 0) {
    for (let i = 0; i < 10; i++) {
        const category = Mock.mock({ 'category|1': Object.keys(categories) }).category;
        const name = Mock.mock({ 'name|1': categories[category] }).name;

        productList.push(
            Mock.mock({
                id: '@id',
                name: name,
                price: '@float(10, 1000, 0, 2)',
                stock: '@integer(0, 1000)',
                description: '@cparagraph(1, 3)',
                category: category,
                imageUrl: '@dataImage("200x200", "商品图片")',
                views: '@integer(0, 10000)',
                sales: '@integer(0, 5000)',
                isRecommended: '@boolean',
                isAvailable: '@boolean',
                isNew: '@boolean'
            })
        );
    }
    saveProductList(productList); // 初始化后保存到 JSON 文件
}

// 获取商品列表
Mock.mock(/\/product\/list/, 'get', () => {
    productList = getProductList(); // 每次获取列表时从 JSON 文件读取最新数据

    const urlParams = new URLSearchParams(options.url.split('?')[1]);
    const page = parseInt(urlParams.get('page'), 10) || 1;
    const pageSize = parseInt(urlParams.get('pageSize'), 10) || 10;

    const start = (page - 1) * pageSize;
    const end = page * pageSize;
    const paginatedItems = productList.slice(start, end);

    return {
        code: 1,
        msg: '获取成功',
        result: paginatedItems,
        total: productList.length,
    };
});

// 添加商品
Mock.mock(/\/product\/add/, 'post', (options) => {
    const { body } = options;
    const newProduct = JSON.parse(body);
    const category = newProduct.category;
    const name = Mock.mock({ 'name|1': categories[category] }).name;
    newProduct.name = name;

    productList.push(Mock.mock(newProduct));
    saveProductList(productList); // 添加后保存到 JSON 文件
    return { code: 1, msg: '添加成功', result: productList };
});

// 编辑商品
Mock.mock(/\/product\/edit/, 'post', (options) => {
    const { body } = options;
    const editedProduct = JSON.parse(body);
    const index = productList.findIndex((ele) => ele.id === editedProduct.id);
    if (index !== -1) {
        const category = editedProduct.category;
        const name = Mock.mock({ 'name|1': categories[category] }).name;
        editedProduct.name = name;

        productList.splice(index, 1, Mock.mock(editedProduct));
        saveProductList(productList); // 编辑后保存到 JSON 文件
    }
    return { code: 1, msg: '修改成功', result: productList };
});

// 获取单个商品
Mock.mock(RegExp(`/product/get.*`), 'get', (options) => {
    const id = options.url.match(/\/product\/get\/(\w+)/)[1];
    const data = productList.find((ele) => ele.id === id);
    return { code: 1, msg: '获取成功', result: data };
});

// 删除商品
Mock.mock(RegExp(`/product/delete.*`), 'delete', (options) => {
    const id = options.url.match(/\/product\/delete\/(\w+)/)[1];
    const index = productList.findIndex((ele) => ele.id === id);
    if (index !== -1) {
        productList.splice(index, 1);
        saveProductList(productList); // 删除后保存到 JSON 文件
    }
    return { code: 1, msg: '删除成功' };
});